<template>
  <view class="create-album-container">
    <view class="form-item">
      <text class="label">相册名称</text>
      <input class="input" v-model="albumForm.name" placeholder="给相册起个名字吧" />
    </view>
    <view class="form-item">
      <text class="label">相册描述</text>
      <textarea class="textarea" v-model="albumForm.description" placeholder="介绍一下这个相册（可选）"></textarea>
    </view>
    <view class="form-item">
      <text class="label">相册封面</text>
      <view class="cover-uploader" @click="chooseCover">
        <image v-if="albumForm.coverUrl" class="cover-preview" :src="safeImageUrl(albumForm.coverUrl)" mode="aspectFill"></image>
        <view v-else class="uploader-placeholder">
          <text class="icon">+</text>
          <text>选择封面</text>
        </view>
      </view>
    </view>

    <!-- AI-Generated Cover -->
    <view class="form-item ai-section">
      <text class="label">🎨 AI生成封面</text>
      <view class="ai-input-container">
        <input class="ai-input" v-model="aiPrompt" placeholder="描述你想要的封面，如：温馨的家庭聚会场景" />
        <button @click="generateAiCover" :disabled="isGenerating" class="ai-generate-btn">
          {{ isGenerating ? '生成中...' : '生成封面' }}
        </button>
      </view>
      <view class="ai-tips">
        <text class="tip-text">💡 提示：描述越详细，生成的封面越符合期望</text>
      </view>
    </view>

    <button class="submit-btn" @click="submitForm" :disabled="loading">{{ loading ? '创建中...' : '创建相册' }}</button>
  </view>
</template>

<script>
import {
  mapState,
  mapActions
} from 'vuex';
import imageHelper from '@/utils/imageHelper';
import config from '@/utils/config.js';
import { api, uploadFile } from '@/utils/request';

export default {
  data() {
    return {
      albumForm: {
        name: '',
        description: '',
        coverUrl: '',
        isPublic: 1,
      },
      loading: false,
      isEditMode: false,
      isSubmitting: false,
      aiPrompt: '',
      isGenerating: false,
    };
  },
  computed: {
    ...mapState('user', ['userInfo']),
  },
  onLoad(options) {
    if (options.id) {
      this.fetchAlbumById(options.id);
      this.isEditMode = true;
    }
  },
  methods: {
    ...mapActions('album', ['createAlbum', 'updateAlbum', 'fetchAlbumById']),
    
    safeImageUrl(url, type = 'cover') {
      console.log('处理图片URL:', url, 'type:', type);
      if (!url) {
        console.log('URL为空，返回默认图片');
        return imageHelper.getDefaultCover();
      }
      if (url.startsWith('http')) {
        console.log('URL是完整HTTP地址:', url);
        return url;
      }
      const finalUrl = imageHelper.safeImageUrl(url);
      console.log('构建的最终URL:', finalUrl);
      return finalUrl;
    },
    async generateAiCover() {
      if (!this.aiPrompt) {
        uni.showToast({ title: '请输入AI绘画的描述', icon: 'none' });
        return;
      }
      
      this.isGenerating = true;
      
      try {
        console.log('开始生成AI封面，提示词:', this.aiPrompt);
        
        const response = await api.post('/image/generate', {
          prompt: this.aiPrompt,
          size: "1024x1024"
        });

        console.log('AI封面生成响应:', response);

        if (response.code === 200 && response.data) {
          let imageUrl = response.data;
          
          // 如果返回的是对象（兼容旧格式）
          if (typeof response.data === 'object' && response.data.imageUrl) {
            imageUrl = response.data.imageUrl;
          }
          
          // 直接保存后端返回的相对路径，显示时再处理
          this.albumForm.coverUrl = imageUrl;
          console.log('设置封面URL:', this.albumForm.coverUrl);
          
          uni.showToast({ title: 'AI封面生成成功', icon: 'success' });
        } else {
          const errorMessage = response.message || 'AI封面生成失败';
          console.error('生成失败:', errorMessage);
          uni.showToast({ title: errorMessage, icon: 'none' });
        }
      } catch (error) {
        console.error('AI封面生成异常:', error);
        uni.showToast({ title: '生成请求失败: ' + (error.message || '未知错误'), icon: 'none' });
      } finally {
        this.isGenerating = false;
      }
    },
    chooseCover() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          const tempFilePath = res.tempFilePaths[0];
          uni.showLoading({ title: '上传封面中...' });
          
          try {
            // 使用统一的上传方法
            const response = await uploadFile({
              url: '/file/upload',
              filePath: tempFilePath,
              name: 'file'
            });

            uni.hideLoading();
            console.log('封面上传响应:', response);
            
            if (response.code === 200) {
              // 直接保存后端返回的相对路径，显示时再处理
              this.albumForm.coverUrl = response.data;
              console.log('封面URL设置为:', this.albumForm.coverUrl);
            } else {
              uni.showToast({
                title: response.message || '封面上传失败',
                icon: 'none'
              });
            }
          } catch (error) {
            console.error('封面上传失败:', error);
            uni.hideLoading();
            uni.showToast({
              title: '封面上传失败',
              icon: 'none'
            });
          }
        }
      });
    },
    async submitForm() {
      if (!this.albumForm.name) {
        uni.showToast({
          title: '请输入相册名称',
          icon: 'none'
        });
        return;
      }
      this.loading = true;
      try {
        console.log('即将创建相册，数据:', this.albumForm);
        await this.createAlbum(this.albumForm);
        uni.showToast({
          title: '创建成功',
          icon: 'success'
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      } catch (error) {
        uni.showToast({
          title: '创建失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.create-album-container {
  padding: 40rpx;
  background-color: #f9f9f9;
  min-height: 100vh;
}

.form-item {
  margin-bottom: 40rpx;
}

.label {
  display: block;
  font-size: 32rpx;
  color: #333;
  margin-bottom: 16rpx;
}

.input,
.textarea {
  width: 100%;
  height: 100rpx;
  padding: 20rpx;
  border-radius: 16rpx;
  background-color: #fff;
  font-size: 30rpx;
  box-sizing: border-box;
  border: 1rpx solid #eee;
}

.textarea {
  height: 200rpx;
}

.cover-uploader {
  width: 200rpx;
  height: 200rpx;
  border-radius: 16rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2rpx dashed #ccc;
  overflow: hidden;

  .cover-preview {
    width: 100%;
    height: 100%;
  }

  .uploader-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #999;

    .icon {
      font-size: 60rpx;
      line-height: 1;
    }
  }
}

.submit-btn {
  background: #007AFF;
  color: white;
  border-radius: 50rpx;
  font-size: 34rpx;
  padding: 24rpx;
  margin-top: 40rpx;
}

.ai-section {
  background-color: #fff;
  padding: 30rpx;
  border-radius: 16rpx;
  border: 2rpx solid #e6f3ff;
  box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.1);
}

.ai-input-container {
  display: flex;
  align-items: center;
  gap: 20rpx;
  width: 100%;
  margin-bottom: 20rpx;
}

.ai-input {
  flex: 1;
  height: 80rpx;
  padding: 20rpx;
  border-radius: 12rpx;
  background-color: #f8f9fa;
  font-size: 28rpx;
  border: 1rpx solid #e9ecef;
  box-sizing: border-box;
}

.ai-generate-btn {
  flex-shrink: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 12rpx;
  font-size: 26rpx;
  padding: 0 24rpx;
  height: 80rpx;
  line-height: 80rpx;
  min-width: 140rpx;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.ai-generate-btn:disabled {
  background: #ccc;
  box-shadow: none;
}

.ai-tips {
  margin-top: 16rpx;
}

.tip-text {
  font-size: 24rpx;
  color: #6c757d;
  line-height: 1.4;
}
</style> 